package com.itita.ww2.game.user.payment;

import com.itita.ww2.core.WW2Exception;
import com.itita.ww2.data.shop.PaymentConfig;
import com.itita.ww2.enums.WW2ExceptionCode;
import com.itita.ww2.game.user.UserRewardDispatch.RewardType;
import com.itita.ww2.model.user.UserProfile;
import com.itita.ww2.puredb.model.UserTimeLimitedPayLog;
import com.itita.ww2.utils.TimeUtil;
import com.smartfoxserver.v2.entities.data.ISFSObject;
import com.smartfoxserver.v2.entities.data.SFSObject;

public class MonthlyCardUtil {
	private UserProfile userProfile;

	public MonthlyCardUtil(UserProfile userProfile) {
		this.userProfile = userProfile;
	}

	public ISFSObject claimMonthlyCardReward(UserTimeLimitedPayLog bean) throws WW2Exception {
		ISFSObject ref = SFSObject.newInstance();
		if (bean == null) {
			bean = UserTimeLimitedPayLog.getByPrimaryKey(userProfile.getUid(), PaymentConfig.MONTHLY_CARD_SKU);
			if (bean == null) {
				throw new WW2Exception(WW2ExceptionCode.NOT_FOUND);
			}
		}
		if (bean.isReceivedToday()) {
			throw new WW2Exception(WW2ExceptionCode.DUPLICATE_OPT);
		}
		int days = bean.getDays();
		if (days == 1) {
			ref = PaymentConfig.getFirstItems(PaymentConfig.MONTHLY_CARD_SKU);
		} else {
			ref = PaymentConfig.getRemainItems(PaymentConfig.MONTHLY_CARD_SKU);
		}
		bean.addReceiveDays(days);
		bean.update();
		userProfile.getRewardManager().onReward(RewardType.TIME_LIMIT_CARD, ref);
		return ref;
	}

	public ISFSObject getMonthlyCardInfo() throws WW2Exception {
		ISFSObject ref = SFSObject.newInstance();
		UserTimeLimitedPayLog bean = UserTimeLimitedPayLog.getByPrimaryKey(userProfile.getUid(),
				PaymentConfig.MONTHLY_CARD_SKU);
		if (bean != null) {
			boolean checkExpire = bean.checkExpire(PaymentConfig.getLimit(PaymentConfig.MONTHLY_CARD_SKU), 3);
			if (checkExpire) {
				ref.putSFSObject("cardInfo", bean.toSFSObject());
			}
		}
		return ref;
	}

	public boolean checkRenewalsAndAddPayItem(String sku) {
		UserTimeLimitedPayLog bean = UserTimeLimitedPayLog.getByPrimaryKey(userProfile.getUid(), sku);
		boolean renewals = checkRenewals(sku, bean);
		if (renewals) {
			bean.delete();
		}
		addTimeLimitedPayItem(sku);
		return renewals;
	}

	private boolean checkRenewals(String sku, UserTimeLimitedPayLog bean) {
		if (bean == null) {
			return false;
		}
		// 存在且保留期内
		return bean.isExpire();
	}

	public void addTimeLimitedPayItem(String sku) {
		UserTimeLimitedPayLog bean = new UserTimeLimitedPayLog();
		bean.setUid(userProfile.getUid());
		bean.setSKU(sku);
		bean.setBuyTime(TimeUtil.getUtcNowMillis());
		bean.setReceiveDays("");
		bean.setExpire(false);
		bean.insert();
	}
}
